package com.example.administrator.ci_edit;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import activity.BaseActivity;
import db.WritingDatabaseHelper;
import entity.Cipai;
import entity.UserConfig;
import entity.Writing;
import fragment.ChangeBackgroundFragment;
import fragment.EditFragment;
import model.Constants;
import okhttp3.Call;
import util.DisplayUtil;
import util.FileUtils;
import util.StringUtils;
import util.TimeUtils;
import wiget.GCDialog;
import wiget.TouchEffectImageView;

import static db.CipaiDatabaseHelper.getCipaiById;
import static db.CipaiDatabaseHelper.getPingzeById;


public class EditActivity extends BaseActivity {

    ChangeBackgroundFragment changeBackgroundFrament;
    EditFragment editFragment;
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    private Cipai cipai = new Cipai();
    private Writing writing;
    private int currentIndex = 0;

    private String oldText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

//        Typeface face = Typeface.createFromAsset (getAssets() , "kaiti.ttf" );
//        introTextView.setTypeface (face);
//        nameTextView.setTypeface(face);

        Log.v("tag", "edit mmp");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);

        Intent intent = getIntent();
        final int id = intent.getIntExtra("extra_id", 60);
        cipai = getCipaiById(id);
        String pingze = getPingzeById(cipai.id);

        // 填新词
        if (cipai != null) {
            Log.v("tag", "xin ci");
            writing = new Writing();
            writing.setId(writing.hashCode());
            writing.setCi_id(cipai.getId());
            writing.setBgimg("0");
            writing.setCipai(cipai);

            cipai.setPingze(pingze);
        }
        // 旧词编辑
        else if (writing != null) {
            cipai = writing.getCipai();
        } else {
            finish();
            Toast.makeText(this, "进入编辑出错", Toast.LENGTH_SHORT).show();
            return;
        }

        oldText = writing.getText();
        getBottomLeftView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                exit();
            }
        });
        setBottomGone();

        initView();
    }

    private void initView() {

        final ImageView edit = new TouchEffectImageView(mActivity, null);
        edit.setScaleType(ScaleType.FIT_XY);
        edit.setImageResource(R.mipmap.layout_bg_edit_selected);

        final ImageView background = new TouchEffectImageView(mActivity, null);
        background.setScaleType(ScaleType.FIT_XY);
        background.setImageResource(R.mipmap.layout_bg_paper);

        final ImageView picture = new TouchEffectImageView(mActivity, null);
        picture.setScaleType(ScaleType.FIT_XY);
        picture.setImageResource(R.mipmap.layout_bg_album);

        edit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                changeFragment(0);
                edit.setImageResource(R.mipmap.layout_bg_edit_selected);
                background.setImageResource(R.mipmap.layout_bg_paper);
                picture.setImageResource(R.mipmap.layout_bg_album);

            }
        });

        background.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                changeFragment(1);
                edit.setImageResource(R.mipmap.layout_bg_edit);
                background.setImageResource(R.mipmap.layout_bg_paper_selected);
                picture.setImageResource(R.mipmap.layout_bg_album);
            }
        });

        picture.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                changeFragment(2);
                edit.setImageResource(R.mipmap.layout_bg_edit);
                background.setImageResource(R.mipmap.layout_bg_paper);
                picture.setImageResource(R.mipmap.layout_bg_album_sel);
            }
        });

        LinearLayout.LayoutParams lps = new LinearLayout.LayoutParams(DisplayUtil.dp2px(mActivity, 40),
                DisplayUtil.dp2px(mActivity, 45));
        lps.leftMargin = 20;
        addBottomCenterView(edit, lps);
        addBottomCenterView(background, lps);
        addBottomCenterView(picture, lps);

        // 创建修改实例
        editFragment = EditFragment.getInstance(cipai, writing);
        changeBackgroundFrament = ChangeBackgroundFragment.getInstance(cipai, writing);

        fragments.add(editFragment);
        fragments.add(changeBackgroundFrament);
        changeFragment(currentIndex);
    }

    public void changeFragment(int pos) {
        currentIndex = pos;
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragments.get(pos));
        transaction.addToBackStack(null);
        transaction.commit();
    }

    public void exit() {

        if (currentIndex == 1) {//// TODO: 2017/7/16 implement BackPress with save() etc.
            changeBackgroundFrament.save();
        }


        if (currentIndex == 1) {
            changeBackgroundFrament.save();
        } else if (currentIndex == 2) {
            //待实现
        }
        editFragment.save();
        if (!StringUtils.isEmpty(writing.getText()) && !writing.getText().equals(oldText)) {
            Bundle bundle = new Bundle();
            bundle.putString(GCDialog.DATA_CONTENT, mActivity.getString(R.string.save_content));
            bundle.putString(GCDialog.DATA_TITLE, mActivity.getString(R.string.save_title));
            bundle.putString(GCDialog.CONFIRM_TEXT, mActivity.getString(R.string.save));
            bundle.putString(GCDialog.CANCEL_TEXT, mActivity.getString(R.string.give_up));
            new GCDialog(mActivity, new GCDialog.OnCustomDialogListener() {

                @Override
                public void onConfirm() {
                    save();
                    finish();
                }

                @Override
                public void onCancel() {
                    finish();


                }
            }, bundle).show();
        } else {
            finish();
        }
    }

    private void save() {
        String whattosave = writing.ToString();
        Log.w("save", whattosave);
        //作品名为当前时间的天干地支表示
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat formatter2 = new SimpleDateFormat("MM");
        SimpleDateFormat formatter3 = new SimpleDateFormat("dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        int year = curDate.getYear();
        String filename = TimeUtils.getTGDZName(year) + "年" + formatter2.format(curDate) + "月"
                + formatter3.format(curDate) + "日" + formatter.format(curDate) +
                cipai.getName() + ".txt";
        //String filename = formatter.format(curDate) + ".txt";
        String filepath = Constants.File_PATH + "/work";
        //WorkReadAndWrite.writeFileSdcard(filename,whattosave);
        FileUtils.writeTxt(filepath, filename, whattosave);

        //send work to sever
        OkHttpUtils.post()
                .url(Constants.SERVER_URL + "login")
                .addParams("username", UserConfig.getUsername())
                .addParams("work_name", filename)
                .addParams("work_content", whattosave)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {

                    }
                });

        WritingDatabaseHelper.saveWriting(mActivity, writing);
    }

    //// TODO: 2017/7/17 how to save
    @Override
    public void onBackPressed() {
        exit();
    }

}